# -*- coding: UTF-8 -*-

from .BaseService import BaseService

class WechatUserMsgInterpterService(BaseService):

    '''
    ... msgContentList的结构
    ... 
    ... 请求正常，返回参数content的值
    ...     "AddMsgList": [
    ...         {
    ...             "ImgWidth": 0,
    ... "FromUserName": "@8c1e63436eabc8250d38712bc76351af90d3a74f618d96b003f6f08201707222", #如果是群消息，格式为"@@7a69eb63860e3362826c5c66b496285c61e8a5ddd93960752d463f0055b90871"
    ...             "PlayLength": 0,
    ...             "OriContent": "",
    ...             "RecommendInfo": {
    ...                 "UserName": "",
    ...                 "Province": "",
    ...                 "City": "",
    ...                 "Scene": 0,
    ...                 "QQNum": 0,
    ...                 "Content": "",
    ...                 "Alias": "",
    ...                 "OpCode": 0,
    ...                 "Signature": "",
    ...                 "Ticket": "",
    ...                 "Sex": 0,
    ...                 "NickName": "",
    ...                 "AttrStatus": 0,
    ...                 "VerifyFlag": 0
    ...             },
    ...             "Content": "ceshi",
    ...             "StatusNotifyUserName": "",
    ...             "StatusNotifyCode": 0,
    ...             "NewMsgId": 7633774691804190000,
    ...             "Status": 3,
    ...             "VoiceLength": 0,
    ...             "ToUserName": "filehelper", #如果是群消息，格式为"@@7a69eb63860e3362826c5c66b496285c61e8a5ddd93960752d463f0055b90871"
    ...             "ForwardFlag": 0,
    ...             "AppMsgType": 0,
    ...             "Ticket": "",
    ...             "EncryFileName": "",
    ...             "AppInfo": {
    ...                 "Type": 0,
    ...                 "AppID": ""
    ...             },
    ...             "Url": "",
    ...             "ImgStatus": 1,
    ...             "MsgType": 1,
    ...             "ImgHeight": 0,
    ...             "MediaId": "",
    ...             "MsgId": "7633774691804189824",
    ...             "FileName": "",
    ...             "HasProductId": 0,
    ...             "FileSize": "",
    ...             "CreateTime": 1522326313,
    ...             "SubMsgType": 0
    ...         }
    ...     ]
    ... }
    '''
    def msgHandler(self, uin, msgList):
        if not msgList or not isinstance(msgList, list):
            return self.core.lib.outputobj(False, '消息列表内容为空')

        operateMsg = []
        for msg in msgList:
            saveAllDataRes = self._saveAllData(msg)
            if saveAllDataRes.success:
                interpretRes = self._interpretMsgStructure(saveAllDataRes.data, uin, msg)
                operateMsg.append('解析数据结结果：%s' % interpretRes.message)
                self.core.lib.stdout(interpretRes.message + "\n", isExit = False)
            else:
                operateMsg.append('原始数据写入失败：%s' % saveAllDataRes.message)

        return self.core.lib.outputobj(True, '|'.join(operateMsg))


    def _saveAllData(self, msg):
        msgType = int(msg.get('MsgType', -1))
        fromUser = msg.get('FromUserName', '')
        toUser = msg.get('ToUserName', '')
        wechatUserOriginalMessageModel = self.core.loader.model('WechatUserOriginalMessageModel')
        return wechatUserOriginalMessageModel.insert(fromUser, toUser, msgType, self.core.loader.module('json').dumps(msg, ensure_ascii = False))


    def _interpretMsgStructure(self, originMsgId, uin, msg):
        content = msg.get('Content', '')
        if not content:
            return self.core.lib.outputobj(False, '消息内容主体为空')

        fromUser = msg.get('FromUserName', '')
        if '@@' in fromUser:
            return self._interpretGroupMsg(originMsgId, uin, msg)

        return self.core.lib.outputobj(False, '非目标消息')


    def _interpretGroupMsg(self, originMsgId, uin, msg):
        fromUser = msg.get('FromUserName')
        content = msg.get('Content')
        msgType = int(msg.get('MsgType', -1))

        insertDict = {
            'origin_msg_id' : originMsgId,
            'group_id' : fromUser[fromUser.rfind('@') + 1:].strip(),
            'from_user' : content[content.find('@') + 1: content.find(':<br/>')],
            'to_user' : msg.get('ToUserName')
        }

        if msgType == 49: #小程序卡片分享、H5链接分享
            insertDict.update(self._interpretNewsMsg(msg))
            wechatGroupShareDataModel = self.core.loader.model('WechatGroupShareDataModel')
            return wechatGroupShareDataModel.insert(insertDict)
        elif msgType == 3: #图片消息
            interpretRes = self._interpretPictureMsg(uin, msg)
            if not interpretRes.success:
                return interpretRes
            wechatGroupShareDataModel = self.core.loader.model('WechatGroupShareDataModel')
            for item in interpretRes.data:
                tmpDict = insertDict.copy()
                tmpDict.update(item)
                res = wechatGroupShareDataModel.insert(tmpDict)
                print res.message
            return self.core.lib.outputobj(True, '数据写入成功')
        else:
            return self.core.lib.outputobj(False, '其它类型消息暂不处理')


    def _interpretNewsMsg(self, msg):
        content = msg.get('Content')
        mRe = self.core.loader.module('re')

        title = msg.get('FileName', '')
        if not title:
            titleData = mRe.search(r'&lt;title&gt;(.+?)&lt;/title&gt;', content)
            title = self._filerCdata(titleData.group(1)).strip() if titleData else ''
        if len(title.decode('utf-8')) > 1000:
            title = title.decode('utf-8')[0:1000]

        shareTypeData = mRe.search(r'&lt;type&gt;(\d+?)&lt;/type&gt;', content)
        shareType = int(self._filerCdata(shareTypeData.group(1))) if shareTypeData else 0

        targetUrl = msg.get('Url', '')
        if not targetUrl:
            targetUrlData = mRe.search('&lt;url&gt;(.+?)&lt;/url&gt;', content)
            targetUrl = self._filerCdata(targetUrlData.group(1)) if targetUrlData else ''
        targetUrl = targetUrl.replace('amp;', '')

        appnameData = mRe.search('&lt;sourcedisplayname&gt;(\S+?)&lt;/sourcedisplayname&gt;', content)
        if not appnameData:
            appnameData = mRe.search('&lt;appname&gt;(\S+?)&lt;/appname&gt;', content)
        appname = self._filerCdata(appnameData.group(1)).strip() if appnameData else ''

        pagepathData = mRe.search('&lt;pagepath&gt;&lt;(.+?)&gt;&lt;/pagepath&gt;', content)
        pagepath = self._filerCdata(pagepathData.group(1)).strip().replace('amp;', '') if pagepathData else ''

        return {
            'source_type' : 2 if pagepath else 1, #1公众号分享，2小程序分享
            'title' : title,
            'appname' : appname,
            'target_url' : targetUrl,
            'share_type' : shareType,
            'pagepath' : pagepath
        }


    def _interpretPictureMsg(self, uin, msg):
        msgId = int(msg.get('NewMsgId', 0))
        if msgId <= 0:
            return self.core.lib.outputobj(False, '图片消息ID为空')

        wechatMediaMessageInterpretService = self.core.loader.service('WechatMediaMessageInterpretService')
        interpretRes = wechatMediaMessageInterpretService.interpretQrcodeImg(uin, msgId)
        if not interpretRes.success:
            return interpretRes

        insertList = []
        for path in interpretRes.data:
            insertDict = {
                'source_type' : 3,  #图片二维码
                'title': '',
                'appname' : '',
                'target_url': path,
                'share_type' : int(msg.get('MsgType', 3)),
                'pagepath' : ''
            }
            insertList.append(insertDict)
        return self.core.lib.outputobj(True, '图片二维码解析成功', insertList)


    def _filerCdata(self, string):
        if 'CDATA[' not in string:
            return string

        return string[string.rfind('[') + 1: string.find(']')]
